/***********************************************************************************************************************
*                                                                                                                      *
* SPLASH build system v0.1                                                                                             *
*                                                                                                                      *
* Copyright (c) 2013 Andrew D. Zonenberg                                                                               *
* All rights reserved.                                                                                                 *
*                                                                                                                      *
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the     *
* following conditions are met:                                                                                        *
*                                                                                                                      *
*    * Redistributions of source code must retain the above copyright notice, this list of conditions, and the         *
*      following disclaimer.                                                                                           *
*                                                                                                                      *
*    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the       *
*      following disclaimer in the documentation and/or other materials provided with the distribution.                *
*                                                                                                                      *
*    * Neither the name of the author nor the names of any contributors may be used to endorse or promote products     *
*      derived from this software without specific prior written permission.                                           *
*                                                                                                                      *
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED   *
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL *
* THE AUTHORS BE HELD LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES        *
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR       *
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE       *
* POSSIBILITY OF SUCH DAMAGE.                                                                                          *
*                                                                                                                      *
***********************************************************************************************************************/

#include "splashcore.h"

using namespace std;

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Construction / destruction

HexFirmwareNode::HexFirmwareNode(
	BuildGraph* graph,
	BuildGraphNode* input,
	std::string arch,
	size_t maxwordsize,
	string name, 
	int width)
	: BuildGraphNode(graph)
	, m_exe(input)
	, m_arch(arch)
	, m_maxwordsize(maxwordsize)
	, m_name(name)
	, m_width(width)
{
	if(m_width != 64)
		m_width = 32;
}

HexFirmwareNode::~HexFirmwareNode()
{
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Dependency scanning

string HexFirmwareNode::GetHash()
{
	DebugPrintfHeading(4, "HexFirmwareNode::GetHash() [node = \"%s\"]\n", m_name.c_str());
	string hashin = "";
	
	//Update our dependencies
	UpdateDependencies();
	
	//Add data at this node
	hashin += sha256(GetOutputPath());	//necessary to ensure static/shared/exe have different hashes
	if(m_width == 64)
		hashin += sha256("64");
	else
		hashin += sha256("32");
	
	//Add data for our dependencies
	for(size_t i=0; i<m_dependencies.size(); i++)
		hashin += m_dependencies[i]->GetHashCached(); 
	return sha256(hashin);
}

void HexFirmwareNode::UpdateDependencies()
{
	DebugPrintfHeading(4, "HexFirmwareNode::UpdateDependencies() [node = \"%s\"]\n", m_name.c_str());
	m_dependencies.clear();
	
	m_dependencies.push_back(m_exe);
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Compilation

string HexFirmwareNode::GetOutputPath()
{
	return m_graph->GetOutDir() + "/" + m_arch + "/" + m_name + ".hex";
}

string HexFirmwareNode::GetDescription()
{
	char desc[1024];
	snprintf(desc, sizeof(desc), "Hex firmware image %s [%s]", m_name.c_str(), m_arch.c_str());
	return string(desc);
}

string HexFirmwareNode::GetBinaryPath()
{
	return m_graph->GetMetaDir() + "/" + GetHashCached()  + "/" + m_name + ".hex";
}

void HexFirmwareNode::Update(Cluster* cluster)
{
	//Rebuild all of our dependencies if necessary
	vector<ClusterJob*> deps;
	for(size_t i=0; i<m_dependencies.size(); i++)
	{		
		BuildGraphNode* node = m_dependencies[i];
		node->UpdateCached(cluster);
		if(node->GetBuildJob() != NULL)
			deps.push_back(node->GetBuildJob());
	}
	
	//Get output directory etc
	string exe_filename = GetBinaryPath();
	string path = GetDirOfFile(exe_filename);
	string base = GetBasenameOfFile(exe_filename);
	string basewe = GetBasenameOfFileWithoutExt(exe_filename);
	
	//Print the heading
	DebugPrintfHeading(3, "Generating hex firmware file %s\n", base.c_str());

	//Create the batch script
	string batch_fname = path + "/hexdump_batch_command_" + basewe + ".sh";
	FILE* fp = fopen(batch_fname.c_str(), "w");
	if(!fp)
		FatalError("Failed to create batch script %s\n", batch_fname.c_str());
	fprintf(fp, "#!/bin/bash\n");
	fprintf(fp, "dd if=/dev/zero of=nulls.bin bs=%d count=%zu > /dev/null 2> /dev/null\n", 
		(m_width == 64) ? 8 : 4, m_maxwordsize);
	if(m_width == 64)
	{
		fprintf(fp, "hexdump -v -e '8/1 \"%%02x\" \"\\n\"' %s > temp.hex\n", m_exe->GetBinaryPath().c_str());
		fprintf(fp, "hexdump -v -e '8/1 \"%%02x\" \"\\n\"' nulls.bin >> temp.hex\n");
	}
	else
	{
		fprintf(fp, "hexdump -v -e '4/1 \"%%02x\" \"\\n\"' %s > temp.hex\n", m_exe->GetBinaryPath().c_str());
		fprintf(fp, "hexdump -v -e '4/1 \"%%02x\" \"\\n\"' nulls.bin >> temp.hex\n");
	}
	fprintf(fp, "cat temp.hex | head -n %zu > %s\n", m_maxwordsize, exe_filename.c_str());
	fprintf(fp, "touch build_successful\n");
	fclose(fp);
	if(0 != chmod(batch_fname.c_str(), 0755))
		FatalError("Failed to set execute permissions on batch script %s\n", batch_fname.c_str());
		
	//Submit the batch script
	m_job = cluster->SubmitBatchJob(batch_fname, cluster->m_cppBuildPartition, path, deps);
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Factory method

HexFirmwareNode* HexFirmwareNode::CreateHexFirmwareNode(
	BuildGraph* graph,
	CppExecutableNode* input,
	size_t maxwordsize,
	string name,	
	bool target,
	int width)
{
	return CreateHexFirmwareNode(graph, input, input->GetArchitecture(), maxwordsize, name, target, width);
}

HexFirmwareNode* HexFirmwareNode::CreateHexFirmwareNode(
	BuildGraph* graph,
	BuildGraphNode* input,
	string arch,
	size_t maxwordsize,
	string name,	
	bool target,
	int width)
{
	//Add the executable node
	HexFirmwareNode* exenode = new HexFirmwareNode(graph, input, arch, maxwordsize, name, width);
	graph->AddNodeWithPath(exenode, exenode->GetOutputPath(), arch);
	
	//Add it as a top-level target if requested
	if(target)
		graph->AddTarget(exenode, exenode->GetTargetName());
	
	//Done
	return exenode;
}

string HexFirmwareNode::GetTargetName() const
{
	return m_name + "-hex-" + m_arch;
}
